#!/usr/bin/python
# -*- coding: utf-8 -*-
# @version        : 1.0
# @Create Time    : 2024/8/29 14:28
# @File           : group
# @IDE            : PyCharm
# @desc           : 描述
from typing import List

from application.settings import CONFIG
from .. import models


class TaskPoolGrouper:
    def __init__(self, tasks: List[models.DCTask]):
        self.tasks = tasks
        self.group_keys = CONFIG.DISPATCH.TASK_GROUP_KEY
        self.group_dict = {}
        self.group_sep = "|"
        self.FINISH_STATUS_LIST = CONFIG.DISPATCH.TASK_FINISH_STATUS

    def split_id(self, _id):
        return _id.split(self.group_sep)

    def join_id(self, value_list):
        return self.group_sep.join(value_list)

    def search_group_by_id(self, _id):
        id_list = self.split_id(_id)
        if len(id_list) == 1:
            return self.group_dict

        group = self.group_dict
        for i in range(1, len(id_list)):
            key = self.join_id(id_list[0:i])
            group = group[key]['children']

        return group

    def group_one_task(self, task):
        for i in range(0, len(self.group_keys)):
            _id = self.join_id([getattr(task, key) if getattr(task, key) is not None else  'UKN' for key in self.group_keys[0: i + 1]])
            group = self.search_group_by_id(_id)
            if _id not in group:
                group[_id] = {
                    "id": _id,
                    "name": getattr(task, self.group_keys[i]) if getattr(task, self.group_keys[i]) is not None else "UKN",
                    "number": 0,
                    "finish": 0,
                    "children": {}
                }
            group[_id]["number"] += 1
            group[_id]["finish"] += 1 if task.status in self.FINISH_STATUS_LIST else 0

    def group_tasks(self):
        for task in self.tasks:
            self.group_one_task(task)

    def dict_to_list(self, group_dict):
        _group_list = list(group_dict.values())
        for item in _group_list:
            item['progress'] = str(round(float(item['finish']) / item['number'] * 100, 2)) + "%"
            if "children" in item:
                item["children"] = self.dict_to_list(item["children"])
        return _group_list

    @property
    def group_list(self):
        return self.dict_to_list(self.group_dict)